package com.checkname.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

@Controller
public class HomeController {
    // 用于存储已经提交过的IP地址
    private Set<String> submittedIPs = new HashSet<>();

    @GetMapping("/index")
    public String getIndexPage() {

        return "index";
    }

    @PostMapping("/index")
    public ResponseEntity<String> markAttendance(HttpServletRequest request, @RequestParam("name") String name) {
        // 一个ip只能提交一次，防止重复提交
        String ipAddress = request.getRemoteAddr(); // 获取客户端的IP地址
        if (submittedIPs.contains(ipAddress)) {
            // 如果IP已经提交过，返回错误消息
            return ResponseEntity.badRequest().body("You have already marked your attendance from this IP address.");
        } else {
            //写入txt，name和当前时间
            try {
                FileWriter fileWriter = new FileWriter("attendance.txt", true);
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
                String time = LocalDateTime.now().toString();
                bufferedWriter.write("\n" + name + "," + time + "," + ipAddress);
                bufferedWriter.close();
                fileWriter.close();
                System.out.println("Successfully wrote to the file.");

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            // 如果IP是第一次提交，将其添加到集合中，并返回成功消息
            submittedIPs.add(ipAddress);

            return ResponseEntity.ok("Attendance marked successfully.");
        }

    }
}